﻿using ASmile.DBModel;
using ASmile.Extend;
using ASmile.ORM.Cores;

namespace ASmile.Com.Da
{
    public class DictAreaBLL : BLLCrudBase<DictAreaSearch, Dict_Area>, IBLLCrud<DictAreaSearch, Dict_Area>
    {
        protected override void SetQuery(QueryCondition<Dict_Area> query, DictAreaSearch arg)
        {
            if (arg.AreaLevel != null && arg.AreaLevel.Length > 0)
            {
                arg.PageNo = 0;
                query.WhereAnd(s => s.WEx_In(s.AreaLevel, arg.AreaLevel));
            }
            else
            {
                if (arg.PCode == null) arg.PCode = string.Empty;
                query.WhereAnd(s => s.PCode == arg.PCode);
                if (arg.SearchVal.IsNotEmpty())
                {
                    string likeStr = $"%{arg.SearchVal}%";
                    query.WhereAnd(s =>
                        s.WEx_Like(s.AreaCode, likeStr) ||
                        s.WEx_Like(s.AreaName, likeStr) ||
                        s.WEx_Like(s.AreaNamePY, likeStr) ||
                        s.WEx_Like(s.AreaNameWB, likeStr));
                }
            }
        }

        protected override ApiResult<string> VerifyModel(Dict_Area model, bool isAdd)
        {
            if (model.AreaLevel <= 0)
            {
                return RetErr("AreaLevel", "区域级别不能为0");
            }
            if (model.AreaCode.IsEmpty())
            {
                return RetErr("AreaCode", "区域编码不能为空");
            }
            if (model.AreaName.IsEmpty())
            {
                return RetErr("AreaName", "区域名称不能为空");
            }
            if (isAdd)
            {
                if (DB.QueryExist<Dict_Area>(s => s.AreaCode == model.AreaCode))
                {
                    return RetErr("AreaCode", "区域编码已存在");
                }
            }
            if (DB.QueryExist<Dict_Area>(s => s.AreaName == model.AreaName && s.AreaCode != model.AreaCode))
            {
                return RetErr("AreaName", "区域名称已存在");
            }
            return RetOK(model.AreaCode, "保存成功");
        }
    }
}